﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Point2PointServer
{
    class Program
    {
        static void Main(string[] args)
        {
            int recv;
            int remotesIndex = 0;
            string[] remotes = new string[2];
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
            Socket udpServer = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(ipep);
            Console.WriteLine("Waiting for a client ...");

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint remote = (EndPoint)sender;
            /*recv = udpServer.ReceiveFrom(data, ref remote);
            Console.WriteLine("Message received from{0}:", remote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data,0, recv));

            string welcome = "Welcome to my test server!";
            data = Encoding.ASCII.GetBytes(welcome);
            udpServer.SendTo(data, data.Length, SocketFlags.None, remote);*/
            while (true) {
                data = new byte[1024];
                recv = udpServer.ReceiveFrom(data, ref remote);

                /*Console.WriteLine("Message from {0}", remote.ToString());
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                udpServer.SendTo(data, recv, SocketFlags.None, remote);*/
                remotes[remotesIndex] = remote.ToString();
                remotesIndex++;

                if(remotesIndex >= 2) {
                    string[] arr = remotes[0].Split(':');
                    IPEndPoint sender1 = new IPEndPoint(IPAddress.Parse(arr[0]), Convert.ToInt32(arr[1]));
                    remote = (EndPoint)sender1;
                    udpServer.SendTo(Encoding.ASCII.GetBytes(remotes[1]),remote);

                    arr = remotes[1].Split(':');
                    IPEndPoint sender2 = new IPEndPoint(IPAddress.Parse(arr[0]), Convert.ToInt32(arr[1]));
                    remote = (EndPoint)sender2;
                    udpServer.SendTo(Encoding.ASCII.GetBytes(remotes[0]), remote);
                    Thread.Sleep(50);
                    break;
                }
            }
            Console.WriteLine("server exit");
            udpServer.Close();
            Console.ReadLine();
        }
    }
}
